using System.Linq;
using Beaker.OpenCube.Render.Lighting;
using Beaker.OpenCube.Render.Materials.Brdfs;
using Beaker.OpenCube.Render.Maths;

namespace Beaker.OpenCube.Render.Materials
{
	public class MatteMaterial
		: Material
	{
		private readonly LambertianBrdf _ambientBrdf;
		private readonly LambertianBrdf _diffuseBrdf;

		public MatteMaterial( Color color, double ambientReflectionCoefficent, double diffuseReflectionCoefficent )
		{
			_ambientBrdf = new LambertianBrdf( ambientReflectionCoefficent, color );
			_diffuseBrdf = new LambertianBrdf( diffuseReflectionCoefficent, color );
		}

		public override Color Shade( Intersection intersection )
		{
			// for every light in the scene
			Vector3 wo = -intersection.Ray.Direction;
			Color color = _ambientBrdf.Rho( intersection, wo ) * intersection.Scene.AmbientLight.GetColor( intersection );

			foreach( ILight light in intersection.Scene.Lights.Where( l => !( l is AmbientLight ) ) )
			{
				Vector3 wi = light.GetDirection( intersection );
				double ndotwi = intersection.Normal * wi;


				if( ndotwi > 0d )
					color += _diffuseBrdf.F( intersection, wo, wi ) * light.GetColor( intersection ) * ndotwi;
			}

			return color;
		}
	}
}